<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="python语法知识5-异常处理与文件操作, blog">
    <meta name="description" content="这是我的个人网站，欢迎来访">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>python语法知识5-异常处理与文件操作 | 头号咸鱼</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

    <script>(function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/7b318e23.js","daovoice")</script>
    

<meta name="generator" content="Hexo 5.3.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/atom.xml" title="头号咸鱼" type="application/atom+xml">
</head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">头号咸鱼</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">头号咸鱼</div>
        <div class="logo-desc">
            
            这是我的个人网站，欢迎来访
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('https://cdn.jsdelivr.net/gh/liangxinxin5102/image2/cartoon01/wallhaven-83yzzo.png')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">python语法知识5-异常处理与文件操作</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/">
                                <span class="chip bg-color">编程语言</span>
                            </a>
                        
                            <a href="/tags/python%E8%AF%AD%E6%B3%95/">
                                <span class="chip bg-color">python语法</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/python/" class="post-category">
                                python
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-02-13
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2021-02-13
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    6.2k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    24 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="一、异常处理"><a href="#一、异常处理" class="headerlink" title="一、异常处理"></a>一、异常处理</h2><h4 id="1-异常类型"><a href="#1-异常类型" class="headerlink" title="1.异常类型"></a>1.异常类型</h4><table>
<thead>
<tr>
<th>异常名称</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>BaseException</td>
<td>所有异常的基类</td>
</tr>
<tr>
<td>SystemExit</td>
<td>解释器请求退出</td>
</tr>
<tr>
<td>KeyboardInterrupt</td>
<td>用户中断执行(通常是输入^C)</td>
</tr>
<tr>
<td>Exception</td>
<td>常规错误的基类</td>
</tr>
<tr>
<td>StopIteration</td>
<td>迭代器没有更多的值</td>
</tr>
<tr>
<td>GeneratorExit</td>
<td>生成器(generator)发生异常来通知退出</td>
</tr>
<tr>
<td>StandardError</td>
<td>所有的内建标准异常的基类</td>
</tr>
<tr>
<td>ArithmeticError</td>
<td>所有数值计算错误的基类</td>
</tr>
<tr>
<td>FloatingPointError</td>
<td>浮点计算错误</td>
</tr>
<tr>
<td>OverflowError</td>
<td>数值运算超出最大限制</td>
</tr>
<tr>
<td>ZeroDivisionError</td>
<td>除(或取模)零 (所有数据类型)</td>
</tr>
<tr>
<td>AssertionError</td>
<td>断言语句失败</td>
</tr>
<tr>
<td>AttributeError</td>
<td>对象没有这个属性</td>
</tr>
<tr>
<td>EOFError</td>
<td>没有内建输入,到达EOF 标记</td>
</tr>
<tr>
<td>EnvironmentError</td>
<td>操作系统错误的基类</td>
</tr>
<tr>
<td>IOError</td>
<td>输入/输出操作失败</td>
</tr>
<tr>
<td>OSError</td>
<td>操作系统错误</td>
</tr>
<tr>
<td>WindowsError</td>
<td>系统调用失败</td>
</tr>
<tr>
<td>ImportError</td>
<td>导入模块/对象失败</td>
</tr>
<tr>
<td>LookupError</td>
<td>无效数据查询的基类</td>
</tr>
<tr>
<td>IndexError</td>
<td>序列中没有此索引(index)</td>
</tr>
<tr>
<td>KeyError</td>
<td>映射中没有这个键</td>
</tr>
<tr>
<td>MemoryError</td>
<td>内存溢出错误(对于Python 解释器不是致命的)</td>
</tr>
<tr>
<td>NameError</td>
<td>未声明/初始化对象 (没有属性)</td>
</tr>
<tr>
<td>UnboundLocalError</td>
<td>访问未初始化的本地变量</td>
</tr>
<tr>
<td>ReferenceError</td>
<td>弱引用(Weak reference)试图访问已经垃圾回收了的对象</td>
</tr>
<tr>
<td>RuntimeError</td>
<td>一般的运行时错误</td>
</tr>
<tr>
<td>NotImplementedError</td>
<td>尚未实现的方法</td>
</tr>
<tr>
<td>SyntaxError</td>
<td>Python 语法错误</td>
</tr>
<tr>
<td>IndentationError</td>
<td>缩进错误</td>
</tr>
<tr>
<td>TabError</td>
<td>Tab 和空格混用</td>
</tr>
<tr>
<td>SystemError</td>
<td>一般的解释器系统错误</td>
</tr>
<tr>
<td>TypeError</td>
<td>对类型无效的操作</td>
</tr>
<tr>
<td>ValueError</td>
<td>传入无效的参数</td>
</tr>
<tr>
<td>UnicodeError</td>
<td>Unicode 相关的错误</td>
</tr>
<tr>
<td>UnicodeDecodeError</td>
<td>Unicode 解码时的错误</td>
</tr>
<tr>
<td>UnicodeEncodeError</td>
<td>Unicode 编码时错误</td>
</tr>
<tr>
<td>UnicodeTranslateError</td>
<td>Unicode 转换时错误</td>
</tr>
<tr>
<td>Warning</td>
<td>警告的基类</td>
</tr>
<tr>
<td>DeprecationWarning</td>
<td>关于被弃用的特征的警告</td>
</tr>
<tr>
<td>FutureWarning</td>
<td>关于构造将来语义会有改变的警告</td>
</tr>
<tr>
<td>OverflowWarning</td>
<td>旧的关于自动提升为长整型(long)的警告</td>
</tr>
<tr>
<td>PendingDeprecationWarning</td>
<td>关于特性将会被废弃的警告</td>
</tr>
<tr>
<td>RuntimeWarning</td>
<td>可疑的运行时行为(runtime behavior)的警告</td>
</tr>
<tr>
<td>SyntaxWarning</td>
<td>可疑的语法的警告</td>
</tr>
<tr>
<td>UserWarning</td>
<td>用户代码生成的警告</td>
</tr>
</tbody></table>
<h4 id="2-异常处理"><a href="#2-异常处理" class="headerlink" title="2.异常处理"></a>2.异常处理</h4><h6 id="try-except语句"><a href="#try-except语句" class="headerlink" title="try/except语句"></a>try/except语句</h6><blockquote>
<p>捕捉异常通常用try（捕捉错误）/except（处理错误）语句。如果你不想在异常发生时结束你的程序，只需在try里捕获它。异常可带参数，用于说明异常原因</p>
</blockquote>
<ul>
<li>形式</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">try:
    检测
except Exception[as reason]:
    出现异常之后的处理代码<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>示例</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">try:
    f = open("F:/ceshi.txt")
    print(f.read())
    f.close()
except OSError:
    print('文件在打开的过程中出错了T_T')<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>打印出具体的原因</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">try:
    f = open("F:/ceshi.txt")
    print(f.read())
    f.close()
except OSError as reason:
    print('文件在打开的过程中出错了T_T\n错误的原因是' + str(reason))<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>一个try语句还可以和多个except语句搭配, 分别与对应的异常进行处理</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">try:
    sum = 1 + '1'
    f = open('一个不存在的文档'.txt)
    print(f.read())
    f.close()
except OSError as reason:
    print('文件在打开的过程中出错了T_T\n错误的原因是' + str(reason))
except TypeError as reason:
    print('类型出错啦T_T\n出错的原因是' + str(reason))<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>对多个异常同一处理</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">try:
    f = open("一个不存在的文档.txt")
    sum = 1 + '1'
    print(f.read())
    f.close()
except (OSError, TypeError) as reason:
    print('出错了T_T\n错误的原因是：' + str(reason))<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h6 id="try-finally语句"><a href="#try-finally语句" class="headerlink" title="try/finally语句"></a>try/finally语句</h6><ul>
<li>try-finally 语句无论是否发生异常都将执行最后的代码。</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">try:
    f = open("F:\代码文件集\python代码文件\小甲鱼入门学习\第9章.异常处理\存在的文档.txt")
    print(f.read())
    sum = 1 + '1'
except (OSError, TypeError) as reason:
    print("出错啦\n出错的原因是" + str(reason))
finally:
    f.close()<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="raise语句"><a href="#raise语句" class="headerlink" title="raise语句"></a>raise语句</h6><ul>
<li>raise语句自己触发异常，自己设置异常（用于bug修改、错误检查）</li>
<li>raise语法格式如下：</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">raise [Exception [, args [, traceback]]]<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<blockquote>
<p>语句中Exception是异常的类型（例如，NameError）参数是一个异常参数值。该参数是可选的，如果不提供，异常的参数是”None”。</p>
</blockquote>
<pre class="line-numbers language-none"><code class="language-none">raise ZeroDivisionError("除数不能为0")<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ul>
<li>最后一个参数是可选的（在实践中很少使用），如果存在，是跟踪异常对象。例子如下：</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">def functionName( level ):

    if level &lt; 1:
        raise Exception("Invalid level!", level)
        # 触发异常后，后面的代码就不会再执行<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>对于自定义的异常，在使用except语句处理异常时，一定要将Exception中的异常名作为except语句的一个参数。例子如下：</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">try:
    #正常逻辑
except "Invalid level!":
    #触发自定义异常
else:
    #其余代码<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="自己创建异常类型，用于常见异常复用"><a href="#自己创建异常类型，用于常见异常复用" class="headerlink" title="自己创建异常类型，用于常见异常复用"></a>自己创建异常类型，用于常见异常复用</h6><ul>
<li>一个异常可以是一个字符串，类或对象。</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">class Networkerror(RuntimeError):  # 基于RuntimeError类创建一个新的类

    def __init__(self, arg):  # 定义一个函数
        self.args = arg
try:
    raise Networkerror("Bad hostname")  #抛出一个Networkerror异常
except Networkerror as e:  #匹配异常的类型，当出现了Networkerror型异常时，执行该except语句，并传递变量e，变量 e 是用于创建Networkerror类的实例，这里的e应该就是这个异常对象？

    print(e.args)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="丰富的else语句"><a href="#丰富的else语句" class="headerlink" title="丰富的else语句"></a>丰富的else语句</h6><ul>
<li>只要try语句中没有问题，就执行else下的语句</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">try:
    sum = 1 + 1
except:
    print("出错了")
else:
    print(sum)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="简洁的with语句-基本语法如下"><a href="#简洁的with语句-基本语法如下" class="headerlink" title="简洁的with语句,基本语法如下"></a>简洁的with语句,基本语法如下</h6><pre class="line-numbers language-none"><code class="language-none">with expression [as target]:
    执行
expression：是一个需要执行的表达式；
arget：是一个变量或者元组，存储的是expression表达式执行返回的结果

with语句的工作原理：
    紧跟with后面的语句会被求值，对象的__enter__()方法被调用，这个方法的返回值将被赋值给as关键
    字后面的变量，当with后面的代码块全部被执行完之后，将调用前面返回对象的__exit__()方法。<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="二、文件操作"><a href="#二、文件操作" class="headerlink" title="二、文件操作"></a>二、文件操作</h2><h4 id="1-I-O函数（不只是文件读写）"><a href="#1-I-O函数（不只是文件读写）" class="headerlink" title="1.I/O函数（不只是文件读写）"></a>1.I/O函数（不只是文件读写）</h4><h6 id="input函数"><a href="#input函数" class="headerlink" title="input函数"></a>input函数</h6><ul>
<li>读取键盘输入，读取输入的行：</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">str = input("请输入：");

print("你输入的内容是: ", str)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<ul>
<li>input() 函数可以接受Python表达式的输入，并输出表达式的计算结果</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">请输入：[x*5 for x in range(2,10,2)]

你输入的内容是: [10, 20, 30, 40]<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<h4 id="2-open函数"><a href="#2-open函数" class="headerlink" title="2.open函数"></a>2.open函数</h4><blockquote>
<p>打开、关闭读写文件。可以用file对象对大多数文件进行操作</p>
</blockquote>
<pre class="line-numbers language-none"><code class="language-none">open(file,mod='r',buffering = -1,encoding=None,errors=None,newline=None,closefd=True,opener=None)<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>


<h6 id="打开文件"><a href="#打开文件" class="headerlink" title="打开文件"></a>打开文件</h6><ul>
<li>你必须先用Python内置的open()函数打开一个文件，创建一个file对象，相关的方法才可以调用它进行读写。</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">file object = open(file_name [, access_mode][, buffering])<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ul>
<li><p>file_name变量是一个包含了你要访问的文件名称的字符串值。</p>
</li>
<li><p>access_mode决定了打开文件的模式：只读，写入，追加等。所有可取值见如下的完全列表。这个参数是非强制的，默认文件访问模式为只读(r)。</p>
</li>
<li><p>如果buffering的值被设为0，就不会有寄存。如果buffering的值取1，访问文件时会寄存行。如果将buffering的值设为大于1的整数，表明了这就是的寄存区的缓冲大小。如果取负值，寄存区的缓冲大小则为系统默认</p>
</li>
<li><p>当文件不存在但通过open函数打开时，如果是写入则会自动创建文件，如果是读取内容则会报错。</p>
</li>
<li><p><strong>文件关闭非常重要</strong></p>
</li>
</ul>
<h6 id="打开模式"><a href="#打开模式" class="headerlink" title="打开模式"></a>打开模式</h6><table>
<thead>
<tr>
<th>打开文件的模式</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td><strong>r</strong></td>
<td>以<strong>只读方式</strong>打开文件。文件的指针将会放在文件的开头。这是<strong>默认</strong>模式。</td>
</tr>
<tr>
<td>rb</td>
<td>以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。</td>
</tr>
<tr>
<td>r+</td>
<td>打开一个文件用于读写。文件指针将会放在文件的开头。</td>
</tr>
<tr>
<td>rb+</td>
<td>以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。</td>
</tr>
<tr>
<td><strong>w</strong></td>
<td>打开一个<strong>文件只用于写入</strong>。如果该<strong>文件已存在则将其覆盖</strong>。如果该文件不存在，创建新文件。</td>
</tr>
<tr>
<td>wb</td>
<td>以二进制格式打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在，创建新文件。</td>
</tr>
<tr>
<td>w+</td>
<td>打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在，创建新文件。</td>
</tr>
<tr>
<td>wb+</td>
<td>以二进制格式打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在，创建新文件。</td>
</tr>
<tr>
<td>a</td>
<td>打开一个文件用于追加。如果该文件已存在，文件指针将会放在文件的结尾。也就是说，新的内容将会被<strong>写入到已有内容之后</strong>。如果该文件不存在，创建新文件进行写入。</td>
</tr>
<tr>
<td>ab</td>
<td>以二进制格式打开一个文件用于追加。如果该文件已存在，文件指针将会放在文件的结尾。也就是说，新的内容将会被写入到已有内容之后。如果该文件不存在，创建新文件进行写入。</td>
</tr>
<tr>
<td>a+</td>
<td>打开一个文件用于读写。如果该文件已存在，文件指针将会放在文件的结尾（不然怎么追加呢）。文件打开时会是追加模式。如果该文件不存在，创建新文件用于读写。</td>
</tr>
<tr>
<td>ab+</td>
<td>以二进制格式打开一个文件用于追加。如果该文件已存在，文件指针将会放在文件的结尾。如果该文件不存在，创建新文件用于读写。</td>
</tr>
<tr>
<td><strong>x</strong></td>
<td>如果文件已存在，使用此模式打开会引发异常</td>
</tr>
<tr>
<td><strong>b</strong></td>
<td>以二进制模式打开</td>
</tr>
<tr>
<td><strong>‘+’</strong></td>
<td>可读写模式，添加到其他模式的后面</td>
</tr>
</tbody></table>
<h6 id="File对象的属性"><a href="#File对象的属性" class="headerlink" title="File对象的属性"></a>File对象的属性</h6><blockquote>
<p>文件被打开后就会创建一个File对象。</p>
</blockquote>
<table>
<thead>
<tr>
<th>对象属性</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>file.closed</td>
<td>返回true如果文件已被关闭，否则返回false。</td>
</tr>
<tr>
<td>file.mode</td>
<td>返回被打开文件的访问模式。</td>
</tr>
<tr>
<td>file.name</td>
<td>返回文件的名称。</td>
</tr>
<tr>
<td>file.softspace</td>
<td>如果用print输出后，必须跟一个空格符，则返回false。否则返回true。</td>
</tr>
<tr>
<td>read(size=-1)</td>
<td>读取size个字符，为负数或者未指定，读取剩下的字符，以字符串的形式返回</td>
</tr>
<tr>
<td>readline（）</td>
<td>从文件中读取一整行字符</td>
</tr>
<tr>
<td>write(str)</td>
<td>写入str字符串</td>
</tr>
<tr>
<td>write(seq)</td>
<td>写入序列字符串seq</td>
</tr>
<tr>
<td>seek（offest，from）</td>
<td>在文件中移动字符串</td>
</tr>
<tr>
<td>tell（）</td>
<td>返回当前文件中的位置</td>
</tr>
</tbody></table>
<h6 id="关闭文件（很重要）"><a href="#关闭文件（很重要）" class="headerlink" title="关闭文件（很重要）"></a>关闭文件（很重要）</h6><ul>
<li>当一个文件对象的引用被重新指定给另一个文件时，Python 会关闭之前的文件（Python会自动地关闭之前的文件对象，这样不那么耗费内存）。用close（）方法关闭文件是一个很好的习惯。</li>
</ul>
<h6 id="文件内定位"><a href="#文件内定位" class="headerlink" title="文件内定位"></a>文件内定位</h6><ul>
<li><p>tell()方法告诉你文件内的当前位置（那应该就是告诉你文件指针在哪个位置）；换句话说，下一次的读写会发生在文件开头这么多字节之后。</p>
</li>
<li><p>seek(offset [,from])方法改变当前文件的位置。Offset变量表示要移动的字节数。From变量指定开始移动字节的参考位置。如果from被设为0，这意味着将文件的开头作为移动字节的参考位置。如果设为1，则使用当前的位置作为参考位置。如果它被设为2，那么该文件的末尾将作为参考位置</p>
</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none"># 打开一个文件
fo = open("foo.txt", "r+")
str = fo.read(10);
print("读取的字符串是 : ", str)

# 查找当前位置
position = fo.tell();
print("当前文件位置 : ", position)

# 把指针再次重新定位到文件开头
position = fo.seek(0, 0);
str = fo.read(10);
print("重新读取字符串 : ", str)
# 关闭打开的文件
fo.close()<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-none"><code class="language-none">'''
读取文件的方法：
    1.使用read(size = -1)函数从文件中读取 size 个字符, 当未给定size值，或者size值为-1时,读取剩余的所有的字符返回
        它是以字节为单位读取
    2.readline()从文件中读取一整行字符串
    3.readlines()从文件中读取每一行字符串并生成一个列表
    4.可以通过tell()方法返回文件指针当前在文件中的位置
'''
f = open("hello.txt", 'r')
print(f.read())
print(f.tell())

'''
seek(offset, from)在文件中移动文件指针, 从from(0表示文件起始位置，1代表当前位置，2代表文件末尾)
   偏移offset个字节
   可以使用该方法将文件指针设置到文件的起始位置
'''
print(f.seek(0, 0))

print(f.readline())

print(f.readlines())
f.seek(0, 0)

#将f文件中的信息存入列表中
print(list(f))

#文件本身支持迭代,可直接用for语句将内容迭代读出来即可：
f.seek(0, 0)

for each_line in f:
    print(each_line)
f.close()<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h6 id="读写文件"><a href="#读写文件" class="headerlink" title="读写文件"></a>读写文件</h6><blockquote>
<p>无论读、写、还是关闭文件，都需要先用open打开文件。</p>
</blockquote>
<pre class="line-numbers language-none"><code class="language-none">

# 写一个文件
fo = open("foo.txt", "wb")
fo.write( "www.runoob.com!\nVery good site!\n");
# 关闭打开的文件
fo.close()

 
# 读一个文件
fo = open("foo.txt", "r+")
str = fo.read(10);   #这里的参数10表示的是被读取的字节数
print("读取的字符串是 : ", str)
# 关闭打开的文件
fo.close()<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="File对象的方法"><a href="#File对象的方法" class="headerlink" title="File对象的方法"></a>File对象的方法</h6><table>
<thead>
<tr>
<th>方法</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>file.close()</td>
<td>关闭文件。关闭后文件不能再进行读写操作。</td>
</tr>
<tr>
<td>file.flush()</td>
<td>刷新文件内部缓冲，直接把内部缓冲区的数据立刻写入文件, 而不是被动的等待输出缓冲区写入。</td>
</tr>
<tr>
<td>file.fileno()</td>
<td>返回一个整型的文件描述符(file descriptor FD 整型), 可以用在如os模块的read方法等一些底层操作上。</td>
</tr>
<tr>
<td>file.isatty()</td>
<td>如果文件连接到一个终端设备返回 True，否则返回 False。</td>
</tr>
<tr>
<td>file.next()</td>
<td>返回文件下一行。</td>
</tr>
<tr>
<td>file.read([size])</td>
<td>从文件读取指定的字节数，如果未给定或为负则读取所有。</td>
</tr>
<tr>
<td>file.readline([size])</td>
<td>读取整行，包括 “\n” 字符。</td>
</tr>
<tr>
<td>file.readlines([sizehint])</td>
<td>读取所有行并返回列表，若给定sizeint&gt;0，返回总和大约为sizeint字节的行, 实际读取值可能比sizhint较大, 因为需要填充缓冲区。</td>
</tr>
<tr>
<td>file.seek(offset[, whence])</td>
<td>设置文件当前位置</td>
</tr>
<tr>
<td>file.tell()</td>
<td>返回文件当前位置。</td>
</tr>
<tr>
<td>file.truncate([size])</td>
<td>截取文件，截取的字节通过size指定，默认为当前文件位置。</td>
</tr>
<tr>
<td>file.write(str)</td>
<td>将字符串写入文件，没有返回值。</td>
</tr>
<tr>
<td>file.writelines(sequence)</td>
<td>向文件写入一个序列字符串列表，如果需要换行则要自己加入每行的换行符。</td>
</tr>
</tbody></table>
<h4 id="3-文件OS（Python中处理文件和目录的模块）"><a href="#3-文件OS（Python中处理文件和目录的模块）" class="headerlink" title="3.文件OS（Python中处理文件和目录的模块）"></a>3.文件OS（Python中处理文件和目录的模块）</h4><h6 id="方法"><a href="#方法" class="headerlink" title="方法"></a>方法</h6><table>
<thead>
<tr>
<th>方法</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>os.access(path, mode)</td>
<td>检验权限模式</td>
</tr>
<tr>
<td>os.chdir(path)</td>
<td>改变当前工作目录</td>
</tr>
<tr>
<td>os.chflags(path, flags)</td>
<td>设置路径的标记为数字标记。</td>
</tr>
<tr>
<td>os.chmod(path, mode)</td>
<td>更改权限</td>
</tr>
<tr>
<td>os.chown(path, uid, gid)</td>
<td>更改文件所有者</td>
</tr>
<tr>
<td>os.chroot(path)</td>
<td>改变当前进程的根目录</td>
</tr>
<tr>
<td>os.close(fd)</td>
<td>关闭文件描述符 fd</td>
</tr>
<tr>
<td>os.closerange(fd_low, fd_high)</td>
<td>关闭所有文件描述符，从 fd_low (包含) 到 fd_high (不包含), 错误会忽略</td>
</tr>
<tr>
<td>os.dup(fd)</td>
<td>复制文件描述符 fd</td>
</tr>
<tr>
<td>os.dup2(fd, fd2)</td>
<td>将一个文件描述符 fd 复制到另一个 fd2</td>
</tr>
<tr>
<td>os.fchdir(fd)</td>
<td>通过文件描述符改变当前工作目录</td>
</tr>
<tr>
<td>os.fchmod(fd, mode)</td>
<td>改变一个文件的访问权限，该文件由参数fd指定，参数mode是Unix下的文件访问权限。</td>
</tr>
<tr>
<td>os.fchown(fd, uid, gid)</td>
<td>修改一个文件的所有权，这个函数修改一个文件的用户ID和用户组ID，该文件由文件描述符fd指定。</td>
</tr>
<tr>
<td>os.fdatasync(fd)</td>
<td>强制将文件写入磁盘，该文件由文件描述符fd指定，但是不强制更新文件的状态信息。</td>
</tr>
<tr>
<td>os.fdopen(fd[, mode[, bufsize]])</td>
<td>通过文件描述符 fd 创建一个文件对象，并返回这个文件对象</td>
</tr>
<tr>
<td>os.fpathconf(fd, name)</td>
<td>返回一个打开的文件的系统配置信息。name为检索的系统配置的值，它也许是一个定义系统值的字符串，这些名字在很多标准中指定（POSIX.1, Unix 95, Unix 98, 和其它）。</td>
</tr>
<tr>
<td>os.fstat(fd)</td>
<td>返回文件描述符fd的状态，像stat()。</td>
</tr>
<tr>
<td>os.fstatvfs(fd)</td>
<td>返回包含文件描述符fd的文件的文件系统的信息，像 statvfs()</td>
</tr>
<tr>
<td>os.fsync(fd)</td>
<td>强制将文件描述符为fd的文件写入硬盘。</td>
</tr>
<tr>
<td>os.ftruncate(fd, length)</td>
<td>裁剪文件描述符fd对应的文件, 所以它最大不能超过文件大小。</td>
</tr>
<tr>
<td>os.getcwd()</td>
<td>返回当前工作目录</td>
</tr>
<tr>
<td>os.getcwdu()</td>
<td>返回一个当前工作目录的Unicode对象</td>
</tr>
<tr>
<td>os.isatty(fd)</td>
<td>如果文件描述符fd是打开的，同时与tty(-like)设备相连，则返回true, 否则False。</td>
</tr>
<tr>
<td>os.lchflags(path, flags)</td>
<td>设置路径的标记为数字标记，类似 chflags()，但是没有软链接</td>
</tr>
<tr>
<td>os.lchmod(path, mode)</td>
<td>修改连接文件权限</td>
</tr>
<tr>
<td>os.lchown(path, uid, gid)</td>
<td>更改文件所有者，类似 chown，但是不追踪链接。</td>
</tr>
<tr>
<td>os.link(src, dst)</td>
<td>创建硬链接，名为参数 dst，指向参数 src</td>
</tr>
<tr>
<td>os.listdir(path)</td>
<td>返回path指定的文件夹包含的文件或文件夹的名字的列表。</td>
</tr>
<tr>
<td>os.lseek(fd, pos, how)</td>
<td>设置文件描述符 fd当前位置为pos, how方式修改: SEEK_SET 或者 0 设置从文件开始的计算的pos; SEEK_CUR或者 1 则从当前位置计算; os.SEEK_END或者2则从文件尾部开始. 在unix，Windows中有效</td>
</tr>
<tr>
<td>os.lstat(path)</td>
<td>像stat(),但是没有软链接</td>
</tr>
<tr>
<td>os.major(device)</td>
<td>从原始的设备号中提取设备major号码 (使用stat中的st_dev或者st_rdev field)。</td>
</tr>
<tr>
<td>os.makedev(major, minor)</td>
<td>以major和minor设备号组成一个原始设备号</td>
</tr>
<tr>
<td>os.makedirs(path[, mode])</td>
<td>递归文件夹创建函数。像mkdir(), 但创建的所有intermediate-level文件夹需要包含子文件夹。</td>
</tr>
<tr>
<td>os.minor(device)</td>
<td>从原始的设备号中提取设备minor号码 (使用stat中的st_dev或者st_rdev field )。</td>
</tr>
<tr>
<td>os.mkdir(path[, mode])</td>
<td>以数字mode的mode创建一个名为path的文件夹.默认的 mode 是 0777 (八进制)。</td>
</tr>
<tr>
<td>os.mkfifo(path[, mode])</td>
<td>创建命名管道，mode 为数字，默认为 0666 (八进制)</td>
</tr>
<tr>
<td>os.mknod(filename[, mode=0600, device])</td>
<td>创建一个名为filename文件系统节点（文件，设备特别文件或者命名pipe）。</td>
</tr>
<tr>
<td>os.open(file, flags[, mode])</td>
<td>打开一个文件，并且设置需要的打开选项，mode参数是可选的</td>
</tr>
<tr>
<td>os.openpty()</td>
<td>打开一个新的伪终端对。返回 pty 和 tty的文件描述符。</td>
</tr>
<tr>
<td>os.pathconf(path, name)</td>
<td>返回相关文件的系统配置信息。</td>
</tr>
<tr>
<td>os.pipe()</td>
<td>创建一个管道. 返回一对文件描述符(r, w) 分别为读和写</td>
</tr>
<tr>
<td>os.popen(command[, mode[, bufsize]])</td>
<td>从一个 command 打开一个管道</td>
</tr>
<tr>
<td>os.read(fd, n)</td>
<td>从文件描述符 fd 中读取最多 n 个字节，返回包含读取字节的字符串，文件描述符 fd对应文件已达到结尾, 返回一个空字符串。</td>
</tr>
<tr>
<td>os.readlink(path)</td>
<td>返回软链接所指向的文件</td>
</tr>
<tr>
<td>os.remove(path)</td>
<td>删除路径为path的文件。如果path 是一个文件夹，将抛出OSError; 查看下面的rmdir()删除一个 directory。</td>
</tr>
<tr>
<td>os.removedirs(path)</td>
<td>递归删除目录。</td>
</tr>
<tr>
<td>os.rename(src, dst)</td>
<td>重命名文件或目录，从 src 到 dst</td>
</tr>
<tr>
<td>os.renames(old, new)</td>
<td>递归地对目录进行更名，也可以对文件进行更名。</td>
</tr>
<tr>
<td>os.rmdir(path)</td>
<td>删除path指定的空目录，如果目录非空，则抛出一个OSError异常。</td>
</tr>
<tr>
<td>os.stat(path)</td>
<td>获取path指定的路径的信息，功能等同于C API中的stat()系统调用。</td>
</tr>
<tr>
<td>os.stat_float_times([newvalue])</td>
<td>决定stat_result是否以float对象显示时间戳</td>
</tr>
<tr>
<td>os.statvfs(path)</td>
<td>获取指定路径的文件系统统计信息</td>
</tr>
<tr>
<td>os.symlink(src, dst)</td>
<td>创建一个软链接</td>
</tr>
<tr>
<td>os.tcgetpgrp(fd)</td>
<td>返回与终端fd（一个由os.open()返回的打开的文件描述符）关联的进程组</td>
</tr>
<tr>
<td>os.tcsetpgrp(fd, pg)</td>
<td>设置与终端fd（一个由os.open()返回的打开的文件描述符）关联的进程组为pg。</td>
</tr>
<tr>
<td>os.tempnam([dir[, prefix]])</td>
<td>返回唯一的路径名用于创建临时文件。</td>
</tr>
<tr>
<td>os.tmpfile()</td>
<td>返回一个打开的模式为(w+b)的文件对象 .这文件对象没有文件夹入口，没有文件描述符，将会自动删除。</td>
</tr>
<tr>
<td>os.tmpnam()</td>
<td>为创建一个临时文件返回一个唯一的路径</td>
</tr>
<tr>
<td>os.ttyname(fd)</td>
<td>返回一个字符串，它表示与文件描述符fd 关联的终端设备。如果fd 没有与终端设备关联，则引发一个异常。</td>
</tr>
<tr>
<td>os.unlink(path)</td>
<td>删除文件路径</td>
</tr>
<tr>
<td>os.utime(path, times)</td>
<td>返回指定的path文件的访问和修改的时间。</td>
</tr>
<tr>
<td>os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])</td>
<td>输出在文件夹中的文件名通过在树中游走，向上或者向下。</td>
</tr>
<tr>
<td>os.write(fd, str)</td>
<td>写入字符串到文件描述符 fd中. 返回实际写入的字符串长度</td>
</tr>
</tbody></table>
<h6 id="示例"><a href="#示例" class="headerlink" title="示例"></a>示例</h6><pre class="line-numbers language-none"><code class="language-none">'''
OS模块中关于文件/目录常用的函数使用方法
'''

import os
#1.getcwd() 返回当前工作目录

print(os.getcwd())

#2.chdir(path) 改变工作目录

os.chdir("F:/")
print(os.getcwd())

#3.listdir(path = '.') 列举指定目录中的文件名('.'表示当前目录，'..'表示上一级目录)

print(os.listdir())
print(os.listdir('F:/代码文件集/python代码文件'))

#4.mkdir(path) 创建单层目录, 如果该目录已存在则抛出异常

os.mkdir('test')

print(os.listdir())

#5.makedirs(path) 递归创建多层目录，如果该目录已存在则抛出异常

os.makedirs('a/b/c')


#在给文件夹下创建一个txt文本

cur_path = os.getcwd()

full_path = cur_path + "wenben.txt"
file = open(full_path, 'w')
file.close()

'''
6.remove(path) 删除指定的文件
    rmdir(path)删除空的单层目录
    removedirs(path) 递归删除多层目录，如果不为空则抛出异常
'''
os.remove('wenben.txt')

os.rmdir('test')

os.removedirs('a/b/c')
print(os.listdir())

#7.rename(old, new) 用于重命名文件或文件夹
os.chdir('F:\代码文件集\python代码文件\小甲鱼入门学习\第8章.文件处理')
os.rename('rename.txt', '8.4.txt')
os.rename('8.4.txt', 'rename.txt')

#8.system(command) 运行系统的shell命令

#os.system('calc') #打开计算器

#9.walk(top) 遍历top参数指定路径下的所有子目录,并将结果返回一个三元组(路径，[包含目录], [包含文件])
for i in os.walk('F:\web作业'):
    print(i)
    
'''
    os.curdir 表示当前目录
    os.pardir 表示上一级目录
    os.sep 表示路径的分隔符
    os.linesep 表示当前平台使用的行终止符
    os.name表示当前使用的操作系统
'''
print(os.curdir)
print(os.pardir)
print(os.sep)
print(os.name)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<blockquote>
<p>参考地址：<a target="_blank" rel="noopener" href="https://github.com/yangshangqi/Learn-Python-with-a-zero-foundation-primer">https://github.com/yangshangqi/Learn-Python-with-a-zero-foundation-primer</a></p>
</blockquote>
<h6 id="OS-path方法"><a href="#OS-path方法" class="headerlink" title="OS.path方法"></a>OS.path方法</h6><blockquote>
<p>参考地址: <a target="_blank" rel="noopener" href="https://docs.python.org/zh-cn/3.8/library/os.path.html">https://docs.python.org/zh-cn/3.8/library/os.path.html</a></p>
</blockquote>
<pre class="line-numbers language-none"><code class="language-none">import os

#1.basename(path)去掉目录路径，单独返回文件名
#2.dirname(path) 去掉文件名，单独返回目录路径
print(os.path.basename('F:\代码文件集\python代码文件\小甲鱼入门学习\第8章.文件处理\\text.txt'))
print(os.path.dirname('F:\代码文件集\python代码文件\小甲鱼入门学习\第8章.文件处理\\text.txt'))

#3.join(path2[, path2[, ..]) 将path1和path2各部分组成一个路径名

print(os.path.join("F:/代码文件集/python代码文件/小甲鱼入门学习"), "第8章.文件处理/text.txt")

#4.split(path) 分割文件名和路径 如果都是目录，也还会将最后一个目录作文文件名分离
#   splitext(path)用于分割文件名和扩展名
print(os.path.split('F:/代码文件集/python代码文件/小甲鱼入门学习/第8章.文件处理/text.txt'))
print(os.path.splitext('F:/代码文件集/python代码文件/小甲鱼入门学习/第8章.文件处理/text.txt'))

#5.getsize(file) 获取文件的大小，以字节为单位

os.chdir("F:\代码文件集\python代码文件\小甲鱼入门学习\第8章.文件处理")
print(os.path.getsize('test.txt'))

#6.getatime() getctime() getmtime() 分别获得文件的最近访问时间、创建时间和修改时间
#   返回值是浮点型秒数, 可用time模块的gmtime()和localtime()函数换算

import time

temp = time.localtime(os.path.getatime('test.txt'))
print("文件被访问的时间是", time.strftime("%d %b %Y %H %M %S"), temp)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="4-pickle模块"><a href="#4-pickle模块" class="headerlink" title="4.pickle模块"></a>4.pickle模块</h4><pre class="line-numbers language-none"><code class="language-none">'''
使用pickle模块可以将列表、字典这类复杂数据结构类型存储为文件,
'''

import pickle
my_list = [123, 3.14, '小甲鱼', ['anther list']]
pickle_file = open("F:\代码文件集\python代码文件\小甲鱼入门学习\第8章.文件处理\my_list.pkl", 'wb')
pickle.dump(my_list, pickle_file)
pickle_file.close()

'''
    用二进制的形式打开文件，使用dump方法向文件中保存该列表信息
    使用的时候只需要用二进制模式打开，然后用load把数据加载进来
'''
pickle_file = open("F:\代码文件集\python代码文件\小甲鱼入门学习\第8章.文件处理\my_list.pkl", 'rb')
my_list = pickle.load(pickle_file)
print(my_list)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">lxx</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="http://xinxinliang.github.io/2021/02/13/python-yu-fa-zhi-shi-5-yi-chang-chu-li-yu-wen-jian/">http://xinxinliang.github.io/2021/02/13/python-yu-fa-zhi-shi-5-yi-chang-chu-li-yu-wen-jian/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">lxx</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/">
                                    <span class="chip bg-color">编程语言</span>
                                </a>
                            
                                <a href="/tags/python%E8%AF%AD%E6%B3%95/">
                                    <span class="chip bg-color">python语法</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="https://gitee.com/liangxinixn/guitar/raw/master/image01/20200726220206.png" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="https://gitee.com/liangxinixn/guitar/raw/master/image01/20200726220308.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2021/02/13/python-yu-fa-zhi-shi-6-mo-fa-fang-fa-sheng-cheng-qi-he-bu-chong/">
                    <div class="card-image">
                        
                        <img src="https://cdn.jsdelivr.net/gh/liangxinxin5102/image2/cartoon01/wallhaven-95mgkw.jpg" class="responsive-img" alt="python语法知识6-魔法方法、生成器和补充">
                        
                        <span class="card-title">python语法知识6-魔法方法、生成器和补充</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-02-13
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/python/" class="post-category">
                                    python
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/">
                        <span class="chip bg-color">编程语言</span>
                    </a>
                    
                    <a href="/tags/python%E8%AF%AD%E6%B3%95/">
                        <span class="chip bg-color">python语法</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2021/02/13/python-yu-fa-zhi-shi-4-han-shu-yu-lei/">
                    <div class="card-image">
                        
                        <img src="https://cdn.jsdelivr.net/gh/liangxinxin5102/image2/cartoon01/wallhaven-73xrmv.png" class="responsive-img" alt="python语法知识4-函数和面向对象">
                        
                        <span class="card-title">python语法知识4-函数和面向对象</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-02-13
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/python/" class="post-category">
                                    python
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/">
                        <span class="chip bg-color">编程语言</span>
                    </a>
                    
                    <a href="/tags/python%E8%AF%AD%E6%B3%95/">
                        <span class="chip bg-color">python语法</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: 头号咸鱼<br />'
            + '文章作者: lxx<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2021</span>
            
            <span id="year">2021</span>
            <a href="/about" target="_blank">lxx</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">272.8k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/xinxinliang" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:1974733812@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1974733812" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1974733812" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    
    <script>
        (function (i, s, o, g, r, a, m) {
            i["DaoVoiceObject"] = r;
            i[r] = i[r] || function () {
                (i[r].q = i[r].q || []).push(arguments)
            }, i[r].l = 1 * new Date();
            a = s.createElement(o), m = s.getElementsByTagName(o)[0];
            a.async = 1;
            a.src = g;
            a.charset = "utf-8";
            m.parentNode.insertBefore(a, m)
        })(window, document, "script", ('https:' == document.location.protocol ? 'https:' : 'http:') +
            "//widget.daovoice.io/widget/6984b559.js", "daovoice")
        daovoice('init', {
            app_id: "7b318e23"
        });
        daovoice('update');
    </script>
    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
